package com.azkj.album.view.base;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alipay.sdk.app.PayTask;
import com.azkj.album.dto.AliPayResult;
import com.azkj.album.dto.CommonBean;
import com.azkj.album.dto.LoginBean;
import com.azkj.album.dto.MessageEvent;
import com.azkj.album.dto.MessageType;
import com.azkj.album.dto.OrderPayBean;
import com.azkj.album.dto.VipInfoBean;
import com.azkj.album.dto.WXPayResultBean;
import com.azkj.album.network.ConfigStorage;
import com.azkj.album.network.NetworkMaster;
import com.azkj.album.network.callback.ServiceCallback;
import com.azkj.album.network.networkframe.bean.BaseResp;
import com.azkj.album.network.networkframe.net.HttpsUtil;
import com.azkj.album.network.networkframe.net.exception.ApiException;
import com.azkj.album.network.utils.ToastUtils;
import com.azkj.album.view.widgets.dialog.DialogHelper;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;


public abstract class BasePayActivity extends BaseActivity {
    private static final int SDK_PAY_FLAG = 1;
    //订单号，用于查询支付状态
//    private String mOrderId;

    private Timer timer = null;//计时器
    private TimerTask task = null;
    protected VipInfoBean vipInfoBean;

    private int is_pay = 0;
    protected IWXAPI mWxApi;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    AliPayResult payResult = new AliPayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        startTime();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        showAlert(PayDemoActivity.this, getString(R.string.pay_failed) + payResult);
                        ToastUtils.showCenterToast("支付失败");
                    }
                    DialogHelper.hideDialog();
                    break;
                }

                default:
                    break;
            }
        }

        ;
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    public abstract void onPaySuccess();


    public void orderPay(int oid, int payItem) {
        Map<String, Object> body = HttpsUtil.getCommonPostRequest();
        body.put("card_id", oid);
        body.put("type", payItem == 0 ? "alipay" : "wechat");


        NetworkMaster.getInstance().getCommonService().orderPay(body, new ServiceCallback<BaseResp<String>>() {
            @Override
            public void onSuccess(BaseResp<String> jsonObj) {
                if (jsonObj.getCode() == BaseResp.CODE_SUCCESS) {

                    if (payItem == 0) {
                        aliPay(jsonObj.getData());
                    } else if (payItem == 1) {
                        wxPay(JSON.parseObject(jsonObj.getData(), WXPayResultBean.class));
                    }


                } else {
                    ToastUtils.showCenterToast(jsonObj.getMsg());
                }
            }

            @Override
            public void onError(ApiException apiException) {
                ToastUtils.showCenterToast("支付失败");
            }

        });


    }

    public void orderQuery() {

        NetworkMaster.getInstance().getCommonService().getVipInfo(new ServiceCallback<BaseResp<VipInfoBean>>() {
            @Override
            public void onSuccess(BaseResp<VipInfoBean> jsonObj) {

                if (jsonObj.getCode() == 1) {
                    is_pay = jsonObj.getData().getIs_vip();
                    if (jsonObj.getData().getVip_time() != null && !jsonObj.getData().getVip_time().equals(vipInfoBean.getVip_time())) {
                        timer.cancel();
                        timer = null;
                        task = null;
                        DialogHelper.hideDialog();
                        vipInfoBean.setIs_vip(1);
                        vipInfoBean.setVip_time(jsonObj.getData().getVip_time());
                        LoginBean userBean = ConfigStorage.getInstance().getUserBean();
                        userBean.getUserinfo().setIs_vip(1);
                        userBean.getUserinfo().setVip_time(vipInfoBean.getVip_time());
                        ConfigStorage.getInstance().saveUserBean(userBean);
                        onPaySuccess();

                    }


                }
            }

            @Override
            public void onError(ApiException apiException) {

            }
        });

    }

    private void aliPay(final String orderInfo) {

        DialogHelper.showLoadingDialog("支付中", -1);

        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(BasePayActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();

    }

    private void wxPay(WXPayResultBean result) {
        if (result == null) {
            ToastUtils.showCenterToast("支付失败");
            return;
        }
        DialogHelper.showLoadingDialog("支付中", -1);
        mWxApi = WXAPIFactory.createWXAPI(this, result.getAppid());

        PayReq request = new PayReq();
        request.appId = result.getAppid();
        request.partnerId = result.getPartnerid();
        request.prepayId = result.getPrepayid();
        request.packageValue = "Sign=WXPay";
        request.nonceStr = result.getNoncestr();
        request.timeStamp = String.valueOf(System.currentTimeMillis() / 1000);
        request.sign = "MD5";
        mWxApi.sendReq(request);

    }

    @Override
    public void onMessage(MessageEvent eventBean) {
        super.onMessage(eventBean);
        if (eventBean.getType() == MessageType.TYPE_ON_WXPAY_RESULT) {
            if ("0".equals(eventBean.getMsg())) {
                startTime();

            } else if ("-2".equals(eventBean.getMsg())) {
                ToastUtils.showCenterToast("支付取消");
                DialogHelper.hideDialog();
            } else {
                ToastUtils.showCenterToast("支付失败");
                DialogHelper.hideDialog();
            }


        }
    }


    //启动
    private void startTime() {

        if (timer == null || task == null) {
            timer = new Timer();
            task = new TimerTask() {
                @Override
                public void run() {
                    if (is_pay == 0) {
                        orderQuery();
                    } else {
                        if (timer != null)
                            timer.cancel();
                        timer = null;
                        task = null;
                    }

                }

            };
            //3000ms执行一次
            timer.schedule(task, 0L, 1500L);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null)
            timer.cancel();
        timer = null;
    }
}